<template>
  <div class="form-container">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>优惠券管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/couponList' }">优惠券列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加优惠券</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="form-content">

      <el-form ref="form" :model="form" :rules="rules" label-width="126px">
        <el-tabs v-model="activeName" @tab-click="handleClick">

          <el-tab-pane label="基本信息" name="first">
            <el-form-item label="排序">
              <el-col :span="5">
                <el-input v-model="form.sort" placeholder="数字越小越靠前"></el-input>
              </el-col>
              <el-col :span="5"><span style="padding-left: 5px;font-size: 12px;">数字越小越靠前</span></el-col>
            </el-form-item>
            <el-form-item label="优惠券名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入优惠券名称"></el-input>
            </el-form-item>
            <el-form-item label="优惠券类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择优惠券类型">
                <el-option label="普通" value="1"></el-option>
                <el-option label="上新" value="2"></el-option>
                <el-option label="爆款" value="3"></el-option>
                <el-option label="优选" value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="使用条件" prop="condition">
              <el-col :span="6">
                <el-input v-model="form.condition" placeholder="消费满多少可用，0表示不限制"></el-input>
                <p style="color: red;">添加后不可修改</p>
              </el-col>
              <el-col :span="5"><span style="padding-left: 5px;font-size: 12px;">消费满多少可用，0表示不限制</span></el-col>
            </el-form-item>
            <el-form-item label="使用时间限制">
              <el-row>
                <el-radio v-model="form.time_type" label="1" border size="medium">获得后</el-radio>
                <el-input v-model="form.date" placeholder="消费满多少可用，0表示不限制" style="width: 492px">
                  <template slot="append">天内有效(0不限制时间使用)</template>
                </el-input>
              </el-row>
              <el-row style="margin-top: 5px">
                <el-radio v-model="form.time_type" label="2" border size="medium">在日期</el-radio>
                <el-date-picker v-model="form.useTimes" type="daterange" placeholder="选择日期"
                                style="width: 260px"></el-date-picker>
              </el-row>
              <p style="color: red;">添加后不可修改</p>
            </el-form-item>
            <el-form-item label="优惠方式">
              <el-row>
                <el-radio v-model="form.discount_type" label="1" border size="medium">立减</el-radio>
                <el-radio v-model="form.discount_type" label="2" border size="medium">打折</el-radio>
                <!-- <el-radio v-model="form.discount_type" label="3" border size="medium">返利</el-radio> -->
              </el-row>
              <el-row>
                <el-input v-if="form.discount_type == '1'" v-model="form.discount_money" class="input-with-select"
                          style="width:31%">
                  <template slot="prepend">立减</template>
                  <template slot="append">元</template>
                </el-input>
                <el-input v-if="form.discount_type == '2'" v-model="form.discount_money" class="input-with-select"
                          style="width:50%">
                  <template slot="prepend">打折</template>
                  <template slot="append">折（该值不能少于0并且不能大于等于1，如：打95折，请输入0.95）</template>
                </el-input>
                <!-- <el-input v-if="form.discount_type == '3'" v-model="form.discount_money" class="input-with-select"
                          style="width:31%">
                  <template slot="prepend">返利</template>
                  <template slot="append">元</template>
                </el-input> -->
                <p style="color: red;">添加后不可修改</p>
              </el-row>
            </el-form-item>
            <el-form-item label="发放总数" prop="num">
              <el-input v-model="form.num" placeholder="优惠券总数量，没有不能领取或发放-1为不限制张数"></el-input>
            </el-form-item>
            <el-form-item label="是否上架">
              <el-switch v-model="form.status"></el-switch>
            </el-form-item>
            <el-form-item label="使用渠道">
              <el-radio v-model="form.sale_type" label="1" border size="medium">默认</el-radio>
              <!-- <el-radio v-model="form.sale_type" label="2" border size="medium">夺宝优惠券</el-radio> -->
              <el-radio v-model="form.sale_type" label="3" border size="medium">活动优惠券</el-radio>
            </el-form-item>
            
            <el-form-item>
              <el-row>
                <el-button type="danger" @click="confirmAdd('form')">立即保存</el-button>
                <el-button type="primary" @click="next('form','two')">下一步</el-button>
                <el-button type="default" @click="cancel()">返回列表</el-button>
              </el-row>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="使用限制" name="two">
            <el-form-item label="优惠使用限制">
              <el-radio v-model="form.rule_type" border size="small" label="1">无优惠使用限制</el-radio><br/>
              <el-radio v-model="form.rule_type" border size="small" label="2">不可与促销优惠同时使用</el-radio><br/>
              <el-radio v-model="form.rule_type" border size="small" label="3">不可与会员折扣同时使用</el-radio><br/>
              <el-radio v-model="form.rule_type" border size="small" label="4">不可与促销优惠和折扣同时使用</el-radio>
            </el-form-item>
            <el-form-item label="是否限制店铺">
              <el-row>
                <el-radio v-model="form.is_store" border size="small" label="0">不限制</el-radio>
                <el-radio v-model="form.is_store" border size="small" label="1">限制以下店铺</el-radio>
              </el-row>
              <el-row>
                <el-select filterable remote reserve-keyword :remote-method="_query_store" v-if="form.is_store=='1'"
                           v-model="form.store_lst"
                           multiple placeholder="请选择店铺" style="width: 100%">
                  <el-option
                    v-for="item in stores"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
            <el-form-item label="商品分类使用限制">
              <el-row>
                <el-radio v-model="form.is_cate_limit" border size="small" label="0">不添加商品分类限制</el-radio>
                <el-radio v-model="form.is_cate_limit" border size="small" label="1">允许以下商品分类使用</el-radio>
              </el-row>
              <el-row>
                <el-select filterable remote reserve-keyword :remote-method="_query_cate" v-if="form.is_cate_limit=='1'"
                           v-model="form.cate_lst"
                           multiple placeholder="请选择商品分类" style="width: 100%">
                  <el-option
                    v-for="item in cates"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
            <el-form-item label="商品使用限制">
              <el-row>
                <el-radio v-model="form.is_product_limit" border size="small" label="0">不添加商品限制</el-radio>
                <el-radio v-model="form.is_product_limit" border size="small" label="1">允许以下商品使用</el-radio>
              </el-row>
              <el-row>
                <el-select filterable remote reserve-keyword :remote-method="_query_good" v-if="form.is_product_limit == '1'"
                           v-model="form.product_lst"
                           multiple placeholder="请选择商品" style="width: 100%">
                  <el-option
                    v-for="item in goods"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="next('form','first')">上一步</el-button>
              <el-button type="danger" @click="confirmAdd('form')">保存</el-button>
              <el-button type="default" @click="cancel()">返回列表</el-button>
            </el-form-item>
          </el-tab-pane>

        </el-tabs>


      </el-form>
    </div>
  </div>

</template>

<script>

  export default {
    components: {},
    data() {
      return {
        validate: false,
        activeName: 'first',
        cates: [],
        goods: [],
        stores: [],
        form: {
          status: 0,
          is_store: '0',
          store_lst: '',
          cate_lst: '',
          product_lst: '',
          time_type: '1',
          useTimes: '',
          date: '',
          condition: '0',//使用条件
          discount_type: '1', //优惠方式 1立减 2打折
          discount_money: '',//优惠金额
          is_product_limit: '0', //商品限制
          rule_type: '1', //使用限制
          is_cate_limit: '0', //商品分类限制
          sort: 100,
          num: '',
          name: '',
          type: '',
          sale_type:'1'
        },
        rules: {
          name: [
            {required: true, message: '请输入优惠券名称', trigger: 'blur'},
          ],
          type: [
            {required: true, message: '请选择优惠券类型', trigger: 'blur'}
          ],
          num: [
            {required: true, message: '请输入优惠券发放总数', trigger: 'blur'},
          ],

        },
        filter_keyword: '',
      }
    },
    methods: {
      handleClick(){

      },
      confirmAdd(form) {
        this.validateFormData(form);
        if (this.validate) {
          const _ths = this;

          const {useTimes, product_lst, store_lst, cate_lst,discount_type,discount_money} = this.form;
          if (discount_type == 2){
            if (discount_money <= 0  || discount_money > 1){
              this.$message.error('折扣必须在0~1之间');
              return false;
            }
          }
          let startTime = this.$moment(useTimes[0]).format('YYYY-MM-DD');
          let endTime = this.$moment(useTimes[1]).format('YYYY-MM-DD');

          this.form.start_time = startTime;
          this.form.end_time = endTime;
          if (product_lst && Array.isArray(product_lst)) {
            console.log('product_lst',product_lst);
            this.form.product_lst = product_lst.join(",");
          }
          if (store_lst && Array.isArray(store_lst)) {
            console.log('store_lst',store_lst);
            this.form.store_lst = store_lst.join(",")
          }
          if (cate_lst && Array.isArray(cate_lst)) {
            console.log('cate_lst',cate_lst);
            this.form.cate_lst = cate_lst.join(",");
          }
          this.$http.post('/api/root/CouponShop/addCoupon', {...this.form})
            .then(rest => {
              if (rest.msg == 'ok') {
                this.$message.success('添加成功');
                setTimeout(function ()  {
                  _ths.$router.push({name: 'couponList'})
                },800)
              } else {
                this.stores = this.goods = this.cates = []
                this.form  = {
                  ...this.form,
                  product_lst:'',
                  store_lst: '',
                  cate_lst: '',
                };
                this.$message.error(rest.msg);
              }
            })
        }
      },
      cancel() {
        this.$router.push({name: 'couponList'})
      },

      next(form, next) {
        this.validateFormData(form);
        if (this.validate) {
          this.activeName = next;
        }
      },
      prev(val) {
        this.activeName = val;
      },
      _query_cate(query) {
        let api = '/api/root/cate/choice';
        this._query_api(api, query,1);
      },
      _query_store(query) {
        let api = '/api/root/storeShop/choice';
        this._query_api(api, query,2);
      },
      _query_good(query) {
        let api = '/api/root/ProductShop/getChoiceProductLst';
        this._query_api(api, query,3);
      },
      _query_api(api, query,type) {
        this.$http.get(api, {keyword: query}).then(rest => {
          if (rest.code == 1) {
            switch (type) {
              case 3:
                this.goods = rest.data;
              case 2:
                this.stores = rest.data;
              case 1:
                this.cates = rest.data;
            }
          }
        });
      },
      /**
       * 验证表单数据
       * @param form
       */
      validateFormData(form) {
        this.$refs[form].validate((valid) => {
          if (!valid) {
            this.$message({
              message: '表单数据未填写完整,操作失败！',
              type: 'warning'
            });
            return false;
          }
          this.validate = true;
          return true;
        })
      },

    }
  }
</script>
<style lang="less" scoped>
  @import "index.less";
</style>